#include "db.h"
#include <QDebug>
#include <QtSql/QSqlDatabase>
#include <QMessageBox>
#include <QtSql/QSqlError>
#include <QSqlQuery>
#include <QStringList>
#include <QCoreApplication>

DB* DB::instance = nullptr;

DB* DB::getInstance()
{
    if (instance == nullptr) {
        instance = new DB();
    }
    return instance;
}
DB::DB(): connectionCounter(0)
{
    // 初始化连接池
    for (int i = 0; i < MAX_CONNECTIONS; ++i) {
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL",QString("Connection_%1").arg(i));
        db.setHostName("localhost");
        db.setDatabaseName("your_database");
        db.setUserName("your_username");
        db.setPassword("your_password");

        if (db.open()) {
            connectionPool.enqueue(db);
        }
    }
}

DB::~DB()
{
    QMutexLocker locker(&mutex);
    // 关闭并移除所有活动连接
    for (const QString& name : activeConnections) {
        {
            QSqlDatabase db = QSqlDatabase::database(name);
            if (db.isOpen()) {
                db.close();
            }
        }
        QSqlDatabase::removeDatabase(name);
    }
}
QString DB::generateConnectionName()
{
    return QString("Connection_%1_%2")
        .arg(reinterpret_cast<quintptr>(QThread::currentThreadId()))
        .arg(++connectionCounter);
}
QSqlDatabase DB::getConnection()
{
    QMutexLocker locker(&mutex);
    QString connectionName = generateConnectionName();

    // 确保在创建连接的线程中进行
    if(QThread::currentThread() != QCoreApplication::instance()->thread()) {
        QSqlDatabase::removeDatabase(connectionName);
        connectionName = QString("Connection_%1").arg(
            reinterpret_cast<quintptr>(QThread::currentThreadId()));
    }

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", connectionName);

    // 创建新的数据库连接
    db.setHostName("localhost");
    db.setDatabaseName("HospitalCSDB");
    db.setUserName("root");
    db.setPassword("shen5858");

    if (db.open()) {
        activeConnections.insert(connectionName);
        return db;
    }

    // 如果连接失败，移除连接
    QSqlDatabase::removeDatabase(connectionName);
    return QSqlDatabase();
}

void DB::releaseConnection(QSqlDatabase& connection)
{
    QMutexLocker locker(&mutex);

    if (connection.isValid()) {
        QString connectionName = connection.connectionName();
        connection.close();
        connection = QSqlDatabase(); // 清空连接对象
        QSqlDatabase::removeDatabase(connectionName);activeConnections.remove(connectionName);
    }
}
bool DB::isConnectionValid(const QSqlDatabase& db)
{
    return db.isValid() && db.isOpen();
}
